package stats

import (
	"epg/consts"
	"epg/jmconf"
	"strings"
	"time"

	"github.com/zeast/logs"
	"gopkg.in/alexcesaro/statsd.v2"
)

//Stater the public stater
var (
	Stater *Stats
)

//Stats the stats
type Stats struct {
	*statsd.Client
}

//Timing (sampleRate float32, bucket string, d time.Duration)
func (s *Stats) Timing(bucket string, d time.Duration) {
	s.Client.Timing(bucket, uint64(d))
}

//Counter (sampleRate float32, bucket string, n int)
func (s *Stats) Counter(bucket string, n int) {
	s.Client.Count(bucket, n)
}

//Gauge (sampleRate float32, bucket string, value interface{})
func (s *Stats) Gauge(bucket string, value uint64) {
	s.Client.Gauge(bucket, value)
}

//GetPrefix return the prefix
func (s *Stats) GetPrefix(p ...string) string {
	return strings.Join(p, ".")
}

//NewStats single a statsd statter.
func NewStats() *Stats {
	if Stater != nil {
		return Stater
	}
	p := strings.ToLower(consts.AppName) + "." + jmconf.Cfg.HostName
	s, err := statsd.New(statsd.Address(jmconf.Cfg.StatsD), statsd.Prefix(p))
	if err != nil {
		logs.Fatalf("初始化 statsD 实例失败. %s", err)
		return nil
	}
	Stater = &Stats{s}
	return Stater
}
